var $quantityTotal=$('#quantityTotal'),$totalPriceTotal=$('#totalPrice'),$cartonTotal=$('#cartonTotal'),$netWeightTotal=$('#netWeightTotal'),$grossWeightTotal=$('#grossWeightTotal');
layui.use(['layer','form','upload','table'], function() {
    var layer = layui.layer, form = layui.form, upload = layui.upload,table=layui.table,orderId = getUrlParam('id'),remainings=[],fn={
        init:function () {
            upload.render({
                elem: '#importExcel',url:rurl('scm/impOrder/auxiliaryInspection'),size:10240,exts:'xls|xlsx'
                ,acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                data:{'orderId':orderId}
                ,before:function (res) {
                    remainings = [];
                    show_loading();
                },done: function(res){
                    if(isSuccessWarn(res)){
                        let data = res.data,members=data.members,auxiliaryInspections=data.auxiliaryInspections;
                        fn.createRows(members);
                        let $materialBody = $('#materialBody');
                        //按2要素匹配
                        $.each(auxiliaryInspections,function (i,o) {
                            let mb =  Base64.encode(o.model.toUpperCase().concat('||').concat(o.brand.toUpperCase()));
                            let mbc =  Base64.encode(o.model.toUpperCase().concat('||').concat(o.brand.toUpperCase()).concat('||').concat(o.country));
                            let $tr = $materialBody.find('tr[mb="'+mb+'"]');
                            if($tr.length>0){
                                //数量是否相等
                                let oquantity = Math.round(parseFloat($($tr[0]).find('input[name="quantity"]').val())*100)/100;
                                let onetWeight = Math.round(parseFloat($($tr[0]).find('input[name="netWeight"]').val())*10000)/10000;
                                let ogrossWeight = Math.round(parseFloat($($tr[0]).find('input[name="grossWeight"]').val())*10000)/10000;
                                let ocarton = parseInt($($tr[0]).find('input[name="cartonNum"]').val());
                                let trhtml = [];
                                trhtml.push('<tr class="txt section '+($($tr[0]).hasClass('double')?'double':'single')+'" forId="'+$($tr[0]).attr('mid')+'" fmbc="'+mbc+'">');
                                trhtml.push('<td></td>');
                                trhtml.push('<td></td>');
                                trhtml.push('<td class="complete">'+o.model+'</td>');
                                trhtml.push('<td></td>');
                                trhtml.push('<td class="complete">'+o.brand+'</td>');
                                trhtml.push('<td></td>');
                                trhtml.push('<td full="quantity" '+(oquantity==o.quantity?'class="complete"':'')+'>'+o.quantity+'</td>');
                                trhtml.push('<td></td>');
                                trhtml.push('<td></td>');
                                trhtml.push('<td full="cartonNum" '+(ocarton == o.carton?'class="complete"':'')+'>'+o.carton+'</td>');
                                trhtml.push('<td full="cartonNo">'+o.rowNo+'</td>');
                                trhtml.push('<td full="netWeight" '+(onetWeight==o.netWeight?'class="complete"':'')+'>'+o.netWeight+'</td>');
                                trhtml.push('<td full="grossWeight" '+(ogrossWeight==o.grossWeight?'class="complete"':'')+'>'+o.grossWeight+'</td>');
                                trhtml.push('<td full="countryName">'+o.country+'</td>');
                                trhtml.push('<td><input type="checkbox" title="确认此验货" lay-skin="primary" lay-filter="checkbox-confirm"></td>');
                                trhtml.push('</tr>');
                                $($tr[0]).after(trhtml.join(''));
                            }else{
                                remainings.push(o);
                            }
                        });
                        $('#showRemainings').html('未匹配上验货数据【'+remainings.length+'】条');
                        //检查验货完成数据
                        let matchQty = 0;
                        let otrs = $materialBody.find('tr[mid]');
                        $.each(otrs,function (i,o) {
                            let othis = $(o),tq = 0.0,tc=0,tn=0.0,tg=0.0;
                            //检查完全匹配条数
                            let ntrs = $('tr[forId="'+othis.attr('mid')+'"][fmbc="'+othis.attr('mbc')+'"]');
                            $.each(ntrs,function (j,k) {
                                let nthis = $(k);
                                tq = Math.round((tq+parseFloat(nthis.find('td[full="quantity"]').text()))*100)/100;
                                tc = tc+parseInt(nthis.find('td[full="cartonNum"]').text());
                                tn = Math.round((tn+parseFloat(nthis.find('td[full="netWeight"]').text()))*10000)/10000;
                                tg = Math.round((tg+parseFloat(nthis.find('td[full="grossWeight"]').text()))*10000)/10000;
                            });
                            //数量，箱数，净重，毛重一致
                            if(tq == (Math.round(parseFloat(othis.find('input[name="quantity"]').val())*100)/100)
                                && tc == parseInt(othis.find('input[name="cartonNum"]').val())
                                && tn == (Math.round(parseFloat(othis.find('input[name="netWeight"]').val())*10000)/10000)
                                && tg == (Math.round(parseFloat(othis.find('input[name="grossWeight"]').val())*10000)/10000)
                            ){
                                ntrs.removeClass('section').addClass('complete');
                                // 完全一致可以隐藏
                                if(ntrs.length==$('tr[forId="'+othis.attr('mid')+'"]').length){
                                    othis.attr({'complete':'true'});
                                }
                                matchQty++;
                            }
                        });
                        $('#matchResult').html('总物料条数【'+otrs.length+'】验货完全匹配条数【'+matchQty+'】');
                        if(otrs.length==matchQty){
                            $('#matchResult').removeClass('def-a').addClass('green-a');
                        }
                        if(matchQty>0){
                            $('#showorhidebtn').attr({'mark':'hide'}).html('隐藏全部匹配数据').show();
                        }else{
                            $('#showorhidebtn').hide();
                        }
                        form.render('checkbox','orderMemberForm');
                    }
                },error:function (index, upload) {
                    hide_loading();
                }
            });
            form.on('checkbox(checkbox-confirm)',function (data) {
                if(data.elem.checked){
                    let $tr = $(data.elem).parent().parent();
                    let mid = $tr.attr('forId');
                    $.each($tr.find('td[full]'),function (i,o) {
                        $('tr[mid="'+mid+'"]').find('input[name="'+$(o).attr('full')+'"]').val($(o).text());
                    });
                    calculationAll($('tr[mid="'+mid+'"]').find('input[name="quantity"]'));
                }
            });
            $('#showRemainings').click(function () {
                layer.open({
                    type: 1,title:'未匹配验货明细',shade:0,
                    area: ['720px', '300px'],
                    content: '<table class="layui-hide" id="remainings-tab"></table>',
                    success:function () {
                        table.render({
                            elem: '#remainings-tab',limit:5000,page:false
                            ,cols: [[
                                {field:'rowNo',title:'序号',width:45,align:'center'}
                                ,{field:'model',title:'型号'}
                                ,{field:'brand',title:'品牌'}
                                ,{field:'quantity',title:'数量',width:60,align:'right'}
                                ,{field:'carton',title:'箱数',width:45,align:'center'}
                                ,{field:'netWeight',title:'净重',width:60,align:'right'}
                                ,{field:'grossWeight',title:'毛重',width:60,align:'right'}
                                ,{field:'country',title:'产地',width:80}
                            ]]
                            , data: remainings
                        });
                    }
                });
            });
            $('.tabBody').css({'max-height':($(window).height()-266)+'px'});

            //保存修改明细
            $('.save-edit-member').click(function () {
                var members = jsonList($('#orderMemberForm').serializeJson());
                if(members.length==0){
                    show_error('请先上传验货数据');return;
                }
                postJSON('scm/impOrder/saveInspectionMemberEdit',{"orderId":orderId,"members":members},function (res) {
                    closeThisWin('修改成功');
                });
            });

            //隐藏显示匹配数据
            $('#showorhidebtn').click(function () {
                let othis = $(this);
                let $otrs = $('#materialBody').find('tr[complete="true"]');
                if(othis.attr('mark')=='hide'){
                    othis.html('显示全部匹配数据').attr({'mark':'show'});
                    $.each($otrs,function (i,o) {
                        $('tr[forId="'+$(o).attr('mid')+'"]').hide();
                    });
                    $otrs.hide();
                }else{
                    othis.html('隐藏全部匹配数据').attr({'mark':'hide'});
                    $.each($otrs,function (i,o) {
                        $('tr[forId="'+$(o).attr('mid')+'"]').show();
                    });
                    $otrs.show();
                }
            });
        }
        ,createRows:function (members) {
            var mhtml = [],tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
            $.each(members,function (i,o) {
                mhtml.push(fn.createRowHtml(i,o));
                tquantity+=o.quantity;ttotalPrice+=o.totalPrice;tcartonNum+=o.cartonNum;tnetWeight+=o.netWeight;tgrossWeight+=o.grossWeight;
            });
            $('#materialBody').html(mhtml.join(''));
            $quantityTotal.html(Math.round(tquantity*100)/100);
            $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
            $cartonTotal.html(tcartonNum);
            $netWeightTotal.html(Math.round(tnetWeight*100)/100);
            $grossWeightTotal.html(Math.round(tgrossWeight*100)/100);
            autoAllModel();
            autoUnit();
            autoCountry();
            initInput();

        },
        createRowHtml:function(i,o){
            let mbc =  Base64.encode(o.model.toUpperCase().concat('||').concat(o.brand.toUpperCase()).concat('||').concat(o.countryName));
            let mb =  Base64.encode(o.model.toUpperCase().concat('||').concat(o.brand.toUpperCase()));
            return [
                '<tr mid="'+o.id+'" class="edit '+(i%2==0?'double':'single')+'" mbc="'+mbc+'" mb="'+mb+'"><td class="t-a-c">'+o.rowNo+'</td>',
                '<td class="t-a-c"><input type="hidden" name="id" LIST value="'+o.id+'"/><span class="'+o.materielStatusId+'">'+o.materielStatusName+'</span></td>',
                '<td><input type="text" name="model" LIST class="layui-input required auto-customer-model" placeholder="型号" value="'+(isEmpty(o.model)?'':o.model)+'"/></td>',
                '<td><input type="text" name="name" LIST class="layui-input" value="'+(isEmpty(o.name)?'':o.name)+'"/></td>',
                '<td><input type="text" name="brand" LIST class="layui-input required" value="'+(isEmpty(o.brand)?'':o.brand)+'"/></td>',
                '<td><input type="text" name="unitName" LIST class="layui-input auto-unit required" value="'+(isEmpty(o.unitName)?'个':o.unitName)+'"/></td>',
                '<td><input type="text" name="quantity" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(o.quantity)?'':o.quantity)+'"/></td>',
                '<td><input type="text" name="unitPrice" LIST class="layui-input layui-disabled" readonly value="'+(isEmpty(o.unitPrice)?'0.0000':o.unitPrice)+'"/></td>',
                '<td><input type="text" name="totalPrice" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(o.totalPrice)?'':o.totalPrice)+'"/></td>',
                '<td><input type="text" name="cartonNum" LIST onblur="calculationAll()" INT class="layui-input required" value="'+(isEmpty(o.cartonNum)?'0':o.cartonNum)+'"/></td>',
                '<td><input type="text" name="cartonNo" LIST class="layui-input required" value="'+(isEmpty(o.cartonNo)?'':o.cartonNo)+'"/></td>',
                '<td><input type="text" name="netWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(o.netWeight)?'0.0000':o.netWeight)+'"/></td>',
                '<td><input type="text" name="grossWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(o.grossWeight)?'0.0000':o.grossWeight)+'"/></td>',
                '<td><input type="text" name="countryName" LIST class="layui-input auto-country required" value="'+(isEmpty(o.countryName)?'中国':o.countryName)+'"/></td>',
                '<td><input type="hidden" name="goodsCode" LIST class="layui-input" value="'+(isEmpty(o.goodsCode)?'':o.goodsCode)+'"/></td>',
                '</tr>'
            ].join('');
        },
    };
    fn.init();
});
function calculationAll(e){
    var tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    if(!isEmpty(e)){
        var $that = $(e),$parent=$that.parent().parent(),$quantity=$parent.find('input[name="quantity"]'),$unitPrice=$parent.find('input[name="unitPrice"]'),$totalPrice=$parent.find('input[name="totalPrice"]');
        switch ($that.attr('name')){
            case 'quantity':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
            case 'unitPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0')*10000)/10000;
                $totalPrice.val(Math.round(quantity*unitPrice*100)/100);
                break;
            case 'totalPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                if(quantity==0.0){$unitPrice.val('0.0000');return;}
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
        }
    }
    $.each($('#materialBody').find('tr'),function (i,o) {
        var $that = $(o);
        tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0')*100)/100;
        ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0')*100)/100;
        tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
        tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0')*10000)/10000;
        tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0')*10000)/10000;
    });
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*100)/100);
    $grossWeightTotal.html(Math.round(tgrossWeight*100)/100);
}